package com.zzw.thread;

import java.util.Map;
import java.util.concurrent.*;

public class CyclicBarrierTest implements Runnable{

    private CyclicBarrier cyclicBarrier = new CyclicBarrier(4,this);
    private Executor executor = Executors.newFixedThreadPool(4);
    private ConcurrentHashMap<String,Integer> count = new ConcurrentHashMap<String, Integer>();

    public void run() {
        int result = 0;
        for (Map.Entry<String,Integer> entry:count.entrySet()){
            result += entry.getValue();
        }
        count.put(Thread.currentThread().getName(),result);
        System.out.println("*********"+Thread.currentThread().getName());
        System.out.println(count);
    }

    public void calculate(){
        for (int i = 0;i < 4;i++){
            executor.execute(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                    count.put(Thread.currentThread().getName(),10);
                    System.out.println(Thread.currentThread().getName() + "is waiting");
                    try {
                        cyclicBarrier.await();
                        System.out.println(Thread.currentThread().getName() + "is working");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public void test(){
        System.out.println("**************" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
       CyclicBarrierTest test  = new CyclicBarrierTest();
       test.calculate();
       test.test();

    }
}
